<?php

namespace backend\controllers;

use Yii;
use backend\models\Upload;
use backend\models\SearchUpload;
use common\components\Helper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
 * UploadController implements the CRUD actions for UploadExcel model.
 */
class UploadController extends Controller
{
//    public $excel = 'blackList';
    public $excel = 'amino';
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all UploadExcel models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SearchUpload();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Upload model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Upload model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Upload();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Upload model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Upload model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Upload model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Upload the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Upload::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionUpload ()
    {
        $model = new Upload();
        $uploadSuccessPath = "";
        if (Yii::$app->request->isPost) {
            $model->file = UploadedFile::getInstance($model, "file");
            //文件上传存放的目录
            $dir = "../public/uploads/".date("Ymd");
            if (!is_dir($dir))
                mkdir($dir);
            if ($model->validate()) {
                //文件名
                $fileName = date("HiiHsHis").$model->file->baseName . "." . $model->file->extension;
                $dir = $dir."/". $fileName;
                $model->file->saveAs($dir);
                $uploadSuccessPath = "/uploads/".date("Ymd")."/".$fileName;
                $model->name = $fileName;
                $model->path = $uploadSuccessPath;
                $model->save();
            }
            if ($model->file->extension == 'xlsx' || $model->file->extension == 'xls') {
                $reader = \PHPExcel_IOFactory::createReader('Excel2007');
                $PHPExcel = $reader->load('../public' . $uploadSuccessPath);
                $objWorksheet = $PHPExcel->getActiveSheet();
                //批量插入
                if ($this->excel == 'blackList') {
                    $blackList = Helper::formatData($objWorksheet->toArray());
                    Yii::$app->db->createCommand()->batchInsert('black_list', [
                        'nick_name',
                        'wechat_num',
                        'created_at',
                        'updated_at',
                    ], $blackList)->execute();
                } else {
                    $aminoList = Helper::formatAmino($objWorksheet->toArray(), $model->file->baseName);
                    Yii::$app->db->createCommand()->batchInsert('amino_acid', [
                        'sheet_name',
                        'sn',
                        'data',
                    ], $aminoList)->execute();
                }
            }
//            $rows = $objWorksheet->getHighestRow();
//            $column = $objWorksheet->getHighestColumn();
            //循环插入
//            $blackList = Helper::formatExcel($objWorksheet->toArray()) ;
//            $BlackListModel = new BlackList();
//            foreach ($blackList as $val) {
//                $_BlackListModel = clone $BlackListModel;
//                $_BlackListModel->nick_name = $val['nick_name'];
//                $_BlackListModel->wechat_num = $val['wechat_num'];
//                $_BlackListModel->save();
//            }




        }
        return $this->render("create", [
            "model" => $model,
            "uploadSuccessPath" => $uploadSuccessPath,
        ]);
    }
}
